#include "common.h"
#include "LcdFunction.h"

/*****************************
	MPU Instruction Function
*****************************/
void E_pulse(void)//when MPU read or write data, E-pulse must be executed.
{
	SetBit(PORTA,E);
	_delay_ms(1); // minimum of interval time of E-pulse : 230ns
	ClearBit(PORTA,E);
}
void InstructionMode(void)
{
	_delay_ms(5);
	ClearBit(PORTA,RS);
	ClearBit(PORTA,RW);
}
void ClearDisp(void)
{
	InstructionMode();
	DB = 0x01;
	E_pulse();
}
void ReturnHome(void)
{
	InstructionMode();
	DB = 0x02;
	E_pulse();
}
void EntryModeSet(int add, int shiftReg)
{
	InstructionMode();
	DB = 0x04 | (add<<1) | (shiftReg<<0);
	E_pulse();
}
void DispOnOff(int disp, int cursor, int blink) // period of blink : 0.4s
{
	InstructionMode();
	DB = 0x08 | (disp<<2) | (cursor<<1) | (blink<<0);
	E_pulse();
}
void CursorDispShift(int shiftCursor, int rightLeft)
{
	InstructionMode();
	DB = 0x10 | (shiftCursor<<3) | (rightLeft<<2);
	E_pulse();	
}
void FunctionSet(int dataLength, int numberOfLine, int fontType)
{
	InstructionMode();
	DB = 0x20 | (dataLength<<4)|(numberOfLine<<3)|(fontType<<2);
	E_pulse();
}





/*****************************
	Initialization Function
*****************************/
void InitLCD(void)
{
	DDRA = 0xF0;//0b11110000
	PORTA = 0x00;

	DDRF = 0xFF;
	PORTF = 0x00;

	_delay_ms(50);//Boot time
	FunctionSet(1,1,0);//DL N F

	_delay_ms(50);//Boot time
	FunctionSet(1,1,0);//DL N F
	
	_delay_ms(5);
	ReturnHome();

	_delay_ms(3);
	DispOnOff(1,1,1);//D C B

	_delay_ms(3);
	ClearDisp();

	_delay_ms(3);
	EntryModeSet(1,0);//ID SH

}


/*****************************
	Function
*****************************/
void SetLCDAddress(unsigned char mode)
{
	ClearBit(PORTA,RS);
	ClearBit(PORTA,RW);

	DB = 0x80 | mode;

	E_pulse();
}
void WriteChar(char ch)
{
	_delay_ms(5);

	SetBit(PORTA,RS);
	ClearBit(PORTA,RW);

	DB = ch;

	E_pulse();
}
void WriteStr(char* str)
{
	while(*str)
		WriteChar(*str++);
}
int BusyFlag(void)
{
	ClearBit(PORTA,RS);
	SetBit(PORTA,RW);

	return PF7;
}
